#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "./lapack-0.3.18.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

if [[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]]; then
    echo "请输入正确的构建路径"
    exit 1
fi
if [[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]]; then
    echo "请输入正确的安装路径"
    exit 1
fi

buildpath=$1
installpath=$2
if [[ "$1" =~ .*/$ ]]; then buildpath=${buildpath%/*}; fi
if [[ "$2" =~ .*/$ ]]; then installpath=${installpath%/*}; fi
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1
set -e 
yum install -y wget tar cmake environment-modules --nogpgcheck
wget -t 20 -c -P "$buildpath" http://www.netlib.org/lapack/lapack-3.8.0.tar.gz
tar xf "$buildpath"/lapack-3.8.0.tar.gz -C "$buildpath" && rm -rf "$buildpath"/lapack-3.8.0.tar.gz
cd "$buildpath"/lapack-3.8.0 || exit 
sed -i '1i\                 REAL Function etime(time)' INSTALL/second_INT_ETIME.f
sed -i '2i\                  REAL time(2)' INSTALL/second_INT_ETIME.f
sed -i '3i\                  Call Cpu_Time(etime)' INSTALL/second_INT_ETIME.f
sed -i '4i\                  time(1) = etime' INSTALL/second_INT_ETIME.f
sed -i '5i\                  time(2) = 0' INSTALL/second_INT_ETIME.f
sed -i '6i\                 End Function' INSTALL/second_INT_ETIME.f
sed -i 's/REAL               ETIME//g' INSTALL/second_INT_ETIME.f
sed -i 's/INTRINSIC          ETIME//g' INSTALL/second_INT_ETIME.f
sed -i 's/T1 = ETIME( TARRAY )/T1 = etime( TARRAY )/g' INSTALL/second_INT_ETIME.f

sed -i '1i\                 REAL Function etime(time)' INSTALL/dsecnd_INT_ETIME.f
sed -i '2i\                  REAL time(2)' INSTALL/dsecnd_INT_ETIME.f
sed -i '3i\                  Call Cpu_Time(etime)' INSTALL/dsecnd_INT_ETIME.f
sed -i '4i\                  time(1) = etime' INSTALL/dsecnd_INT_ETIME.f
sed -i '5i\                  time(2) = 0' INSTALL/dsecnd_INT_ETIME.f
sed -i '6i\                 End Function' INSTALL/dsecnd_INT_ETIME.f
sed -i 's/REAL               ETIME//g' INSTALL/dsecnd_INT_ETIME.f
sed -i 's/INTRINSIC          ETIME//g' INSTALL/dsecnd_INT_ETIME.f
sed -i 's/T1 = ETIME( TARRAY )/T1 = etime( TARRAY )/g' INSTALL/dsecnd_INT_ETIME.f

cp make.inc.example make.inc
sed -i 's/gcc/clang/g' make.inc
sed -i 's/gfortran/flang/g' make.inc
sed -i 's/librefblas.a/libblas.a/g' make.inc

make -j $(nproc)
cp *.a "$installpath"/openblas/lib

rm -rf "$buildpath"/lapack-3.8.0
